// See https://aka.ms/new-console-template for more information
using FileEncoding;
using System.Text;

System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
Encoding utf8 = Encoding.GetEncoding(65001);//使用code page

Encoding gb2312 = Encoding.GetEncoding("gb2312");//通过bodyname

var tmpDir = Environment.CurrentDirectory;
var getFiles = Directory.GetFiles(tmpDir, "*.sql", SearchOption.TopDirectoryOnly);

Console.WriteLine($"开始合并Sql:{tmpDir},count:{getFiles?.Length}");

var defaultAll = Path.Combine(tmpDir, "MergeAll.sql");

var allContent = new StringBuilder();
foreach (string getFile in getFiles)
{
    var tmpname = Path.GetFileNameWithoutExtension(getFile);
    if (tmpname == "MergeAll")
    {
        continue;
    }
    using (StreamReader sr = new StreamReader(getFile, EncodingType.GetType(getFile)))
    {
        string sTemp = sr.ReadToEnd().Trim();
        string sCurEncode = sr.CurrentEncoding.EncodingName;

        allContent.AppendLine($"----filename: {tmpname}");
        allContent.AppendLine(sTemp);
        if (!sTemp.EndsWith("go", StringComparison.OrdinalIgnoreCase))
        {
            allContent.AppendLine("GO");
        }
    }

}

File.WriteAllText(defaultAll, allContent.ToString(), Encoding.UTF8);

Console.WriteLine($"完成合并：{defaultAll}");

Console.ReadLine();


static string GB2312ToUTF8(string str)
{
    try
    {
        Encoding gb2312 = Encoding.GetEncoding("gb2312");
        Encoding utf8 = Encoding.GetEncoding(65001);
        byte[] gb2312Bytes = gb2312.GetBytes(str);
        byte[] utf8Bytes = Encoding.Convert(gb2312, utf8, gb2312Bytes);
        string result = utf8.GetString(utf8Bytes);
        return result;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
        return str;
    }
}

/// <summary> 
/// FileEncoding 的摘要说明 
/// </summary> 
namespace FileEncoding
{
    /// <summary> 
    /// 获取文件的编码格式 
    /// </summary> 
    public class EncodingType
    {
        /// <summary> 
        /// 给定文件的路径，读取文件的二进制数据，判断文件的编码类型 
        /// </summary> 
        /// <param name=“FILE_NAME“>文件路径</param> 
        /// <returns>文件的编码类型</returns> 
        public static System.Text.Encoding GetType(string FILE_NAME)
        {
            FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
            var r = GetType(fs);

            if (r.Item1 && IsGB2312(FILE_NAME))
            {
               return Encoding.GetEncoding("GB2312");
            }

            fs.Close();
            return r.Item2;
        }

        /// <summary> 
        /// 通过给定的文件流，判断文件的编码类型 
        /// </summary> 
        /// <param name=“fs“>文件流</param> 
        /// <returns>文件的编码类型</returns> 
        public static (bool,System.Text.Encoding) GetType(FileStream fs)
        {
            byte[] Unicode = new byte[] { 0xFF, 0xFE, 0x41 };
            byte[] UnicodeBIG = new byte[] { 0xFE, 0xFF, 0x00 };
            byte[] UTF8 = new byte[] { 0xEF, 0xBB, 0xBF }; //带BOM 
            Encoding reVal = Encoding.Default;
            bool isDefault = false;

            BinaryReader r = new BinaryReader(fs, System.Text.Encoding.Default);
            int i;
            int.TryParse(fs.Length.ToString(), out i);
            byte[] ss = r.ReadBytes(i);
            if (IsUTF8Bytes(ss) || (ss[0] == 0xEF && ss[1] == 0xBB && ss[2] == 0xBF))
            {
                reVal = Encoding.UTF8;
            }
            else if (ss[0] == 0xFE && ss[1] == 0xFF && ss[2] == 0x00)
            {
                reVal = Encoding.BigEndianUnicode;
            }
            else if (ss[0] == 0xFF && ss[1] == 0xFE && ss[2] == 0x41)
            {
                reVal = Encoding.Unicode;
            }
            else
            {
                isDefault = true;
                reVal = Encoding.Default;
            }
            r.Close();
            return (isDefault,reVal);

        }
        public static bool IsGB2312(string filePath)
        {
            byte[] buffer = new byte[3];
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                fs.Read(buffer, 0, buffer.Length);
            }

            // 排除带 BOM 的编码（如 UTF-8）
            if (buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF)
            {
                return false; // UTF-8 with BOM
            }

            // 读取完整文件内容并验证 GB2312 字符范围
            string content = File.ReadAllText(filePath, Encoding.GetEncoding("GB2312"));
            foreach (char c in content)
            {
                if (IsGB2312Character(c))
                {
                    return true; // 存在 GB2312 字符
                }
            }
            return false;
        }

        private static bool IsGB2312Character(char c)
        {
            byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(c.ToString());
            if (bytes.Length != 2) return false; // GB2312 汉字为双字节

            byte byte1 = bytes[0];
            byte byte2 = bytes[1];
            // GB2312 汉字范围：首字节 0xB0-0xF7，次字节 0xA0-0xFE [3,5](@ref)
            return (byte1 >= 0xB0 && byte1 <= 0xF7) &&
                   (byte2 >= 0xA0 && byte2 <= 0xFE);
        }

        /// <summary> 
        /// 判断是否是不带 BOM 的 UTF8 格式 
        /// </summary> 
        /// <param name=“data“></param> 
        /// <returns></returns> 
        private static bool IsUTF8Bytes(byte[] data)
        {
            int charByteCounter = 1; //计算当前正分析的字符应还有的字节数 
            byte curByte; //当前分析的字节. 
            for (int i = 0; i < data.Length; i++)
            {
                curByte = data[i];
                if (charByteCounter == 1)
                {
                    if (curByte >= 0x80)
                    {
                        //判断当前 
                        while (((curByte <<= 1) & 0x80) != 0)
                        {
                            charByteCounter++;
                        }
                        //标记位首位若为非0 则至少以2个1开始 如:110XXXXX...........1111110X 
                        if (charByteCounter == 1 || charByteCounter > 6)
                        {
                            return false;
                        }
                    }
                }
                else
                {
                    //若是UTF-8 此时第一位必须为1 
                    if ((curByte & 0xC0) != 0x80)
                    {
                        return false;
                    }
                    charByteCounter--;
                }
            }
            if (charByteCounter > 1)
            {
                throw new Exception("非预期的byte格式");
            }
            return true;
        }

    }


}